<?
if ( ! function_exists('is_post')){
	function is_post($type){
	if(strlen($type) == 0)
		return false;
	else{
		if(isset($_POST[$type]))
			return $_POST[$type];
		else
			return false;
	}
}
}

if ( ! function_exists('is_get')){
	function is_get($key){
		if(strlen($key) == 0)
			return false;
		else{
			if(isset($_GET[$key]))
				return $_GET[$key];
			else
				return false;
		}
	}
}

if ( ! function_exists('is_request')){
	function is_request($key){
		if(strlen($key) == 0)
			return false;
		else{
			if(isset($_REQUEST[$key]))
				return $_REQUEST[$key];
			else
				return false;
		}
	}
}

function wpts_select_shoot_data($shoot_id, $individual_shoot_id = false){
global $wpdb;
	$sql = "SELECT * from $wpdb->posts
	LEFT JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.id
	WHERE `".$wpdb->posts."`.`post_type` = 'wpts_shoot'
	AND `".$wpdb->term_relationships."`.`term_taxonomy_id` = $shoot_id

	";
	if ($individual_shoot_id )
		$sql .= " AND `".$wpdb->posts."`.`ID` = $individual_shoot_id ";
	$sql .= "ORDER BY `".$wpdb->posts."`.post_name DESC";
	$shoot = $wpdb->get_results($sql);
	return $shoot;
	//return $sql;
}

function wpts_select_individual_shoot_data($individual_shoot_id){
	global $wpdb;
	$sql = "SELECT * from $wpdb->posts
	WHERE `".$wpdb->posts."`.`post_type` = 'wpts_shoot'
	AND `".$wpdb->posts."`.`ID` = $individual_shoot_id ";
	$shoot = $wpdb->get_row($sql);
	return $shoot;


}

function wpts_get_season_shoots($season_id){
	$shoots_in_season = get_term_children($season_id, 'wpts_shoots');
	foreach ($shoots_in_season as $shoot){
		$shoots_info[] = get_term($shoot, 'wpts_shoots', 'ARRAY_A');
	}
	return $shoots_info;
}

function wpts_get_season_start_date($season_id){
	$shoots_in_season = wpts_get_season_shoots($season_id);
	foreach ($shoots_in_season as $shoot){
		$shootdata = unserialize( $shoot['description'] );
		if (! isset($first) ){
			$date = $shootdata['date'];
			$date = (int) $date{0} . (int) $date{1} . (int) $date{2} . (int) $date{3} . (int) $date{5} . (int) $date{6} . (int) $date{8} . (int) $date{9};
			$first = $date;
		} else {
			$date = $shootdata['date'];
			$date = (int) $date{0} . (int) $date{1} . (int) $date{2} . (int) $date{3} . (int) $date{5} . (int) $date{6} . (int) $date{8} . (int) $date{9};
			if ($first > $date)
				$first = $date;
			//else $first = 'fail';
		}
	}
	return (int)$first;
}

function wpts_calculate_class($average){
// Get all of the shoots
	if ($average >= 94.5 )
		return 'AAA';
	elseif ($average >= 91 )
		return 'AA';
	elseif ($average >= 88 )
		return 'A';
	elseif ($average >= 85.5 )
		return 'B';
	elseif ($average >= 81.5 )
		return 'C';
	elseif ($average >= 78 )
		return 'D';
	else
		return 'E';
}

function wpts_wwtsl_shoots_for_classes($season_id, $shoot_id, $shooter_id){
	$scores = wpts_get_shoots_for_avg($season_id, $shoot_id, $shooter_id, 5);
	$a=0;
	$sum = 0;
	if ($scores){
		foreach ($scores as $score){
			$sum += (float)$score;
			$a++;
		}
	$it = (float)$sum/$a;
	} else {
	return false;
	break;
	}
	return $it;

}

function wpts_con_class($bday, $season_id){
	$birthday = (int) $bday{0} . (int) $bday{1} . (int) $bday{2} . (int) $bday{3} . (int) $bday{5} . (int) $bday{6} . (int) $bday{8} . (int) $bday{9};
	$birthday = (int) $birthday;
	$start = wpts_get_season_start_date($season_id);
    $age = (int)(($start - $birthday)/10000);

	if ($age <= 13)
		return 'Sub-Junior';
	elseif ($age <= 18)
		return 'junior';
	elseif ($age <= 40)
		return '3Sub Senior';
	elseif ($age <= 50)
		return '2Sub Senior';
	elseif ($age <= 60)
		return '1Sub Senior';
	elseif ($age <= 70)
		return 'Senior';
	else
		return 'Veteran';

}

function wpts_get_shoot_data($shoot_id, $individual_shoot_id = false){
	$shoots = wpts_select_shoot_data($shoot_id, $individual_shoot_id);
	$a=0;
	foreach ($shoots as $shoot){
		$data[$a]['score'] = $shoot->post_title;
		$data[$a]['result'] = $shoot->post_name;
		$data[$a]['id'] = $shoot->ID;
		$data[$a]['shoot_id'] = $shoot->term_taxonomy_id;
		$shoot_info = get_term_by('id', $shoot->term_taxonomy_id, 'wpts_shoots', $output = ARRAY_A);
		$data[$a]['shoot_name'] = $shoot_info['name'];
		$data[$a]['shooter_id'] = $shoot->post_author;
		$shooter =  get_userdata( $shoot->post_author );
		$data[$a]['shooter_name']['full'] =	$shooter->display_name ;
		$data[$a]['shooter_name']['first'] = $shooter->user_firstname;
		$data[$a]['shooter_name']['last'] = $shooter->user_lastname;
		$data[$a]['shooter_club'] =  $shooter->shootclub;
		$bday = $shooter->bday;

		$data[$a]['conclass'] = wpts_con_class($bday, $shoot_info['parent']);
		$data[$a]['season_id'] = $shoot_info['parent'];
		$data[$a]['avg_for_class'] = wpts_wwtsl_shoots_for_classes($shoot_info['parent'], $shoot->term_taxonomy_id, $shoot->post_author);
		$data[$a]['class_scores'] = wpts_calculate_class($data[$a]['avg_for_class']);
		$data[$a]['avg'] = wpts_season_avg($shoot_info['parent'], $shoot->term_taxonomy_id, $shoot->post_author);
		$data[$a]['first_miss'] = get_post_meta($shoot->ID,'first_miss', true);
		$a++;

	}
	if (! isset($data) )
		$data = false;
	return $data;
}

/*Process shortcode
 *
 * @param shortcode attribute (shoot_id)
 * @return table or message if error
 */

function wpts_show_shoot($atts){
	extract(shortcode_atts(array('shoot_id' => false), $atts));
	if (! $shoot_id){
		$table = "No shoot used";
	}
	$table = get_option("wpts_shoot_table_$shoot_id");
	if ( empty($table) ){
		$ind_shoot_table =  wpts_ind_shoot_result_table($shoot_id);
		if (! $ind_shoot_table ){
			$table = "No scories exist for this event";
		} else {
			$season  = wpts_season_to_date_table($shoot_id);
			ob_start();
			{ // buffer start
				echo $ind_shoot_table;
				echo $season;
				$table = ob_get_clean();
			} // end buffer

		}
	add_option("wpts_shoot_table_$shoot_id", $table, '', 'no');
	}

	add_action('wp_footer', 'wpts_tablesorter_init');
	return $table;


}

function wpts_tablesorter_init(){
echo '
<script type="text/javascript">
jQuery(document).ready(function($) {

    {
        $(".tablesorter").tablesorter();
    }
});
</script>

';

}

function wpts_tablesorter(){
	wp_enqueue_script( 'tablesorter',plugins_url('/wp-targetshooting/tablesorter/jquery.tablesorter.min.js'), array('jquery'), '1.0');
	wp_enqueue_style( 'tablesorter',plugins_url('/wp-targetshooting/tablesorter/themes/blue/style.css') );
}

function wpts_season_to_date_table( $shoot ){
	$seasondata = wpts_get_season_data( $shoot);
	ob_start(); {


			echo "<table class='tablesorter'>
					<thead>
					<tr>
						<th>Last</th>
						<th>First</th>
						<th>Club</th>
						<th>Concur</th>
						<th>Class</th>";
		foreach ($seasondata['shoots'] as $shoots ){
			echo "<th>".$shoots['name']."</th>";
			$all_shoots[] = $shoots['term_id'];
		}

			echo "	</tr>
					</thead>";

	foreach ($seasondata['theshoots'] as $shooter ){


		echo "<tr>";
		echo "<td>".$shooter['lname']."</td>";
		echo "<td>".$shooter['fname']."</td>";
		echo "<td>".$shooter['shooter_club']."</td>";
		echo "<td>".$shooter['concur']."</td>";
		echo "<td>".$shooter['class']."</td>";
		foreach ($all_shoots as $shoot){
			if ( isset($shooter[$shoot]) )
				echo "<td>".$shooter[$shoot]['score']."</td>";
			else
				echo "<td>n/a</td>";
		}

		echo "</tr>";

	}
		echo "</table>";
	} // end ob
	$table = ob_get_clean();
	return $table;

}

function wpts_shoot_result_to_array($shoot){
		$shoot_result['score'] = $shoot->post_title;
		$shoot_result['result'] = $shoot->post_name;
		$shoot_result['id'] = $shoot->ID;
		$shoot_result['shoot_id'] = $shoot->term_taxonomy_id;
		$shoot_info = get_term_by('id', $shoot->term_taxonomy_id, 'wpts_shoots', $output = ARRAY_A);
		$shoot_result['shoot_name'] = $shoot_info['name'];
		$shoot_result['shooter_id'] = $shoot->post_author;
		$shooter =  get_userdata( $shoot->post_author );
		$shoot_result['shooter_name']['full'] =	$shooter->display_name ;
		$shoot_result['shooter_name']['first'] = $shooter->user_firstname;
		$shoot_result['shooter_name']['last'] = $shooter->user_lastname;
		$shoot_result['shooter_club'] =  $shooter->shootclub;
		$bday = $shooter->bday;

		$shoot_result['conclass'] = wpts_con_class($bday, $shoot_info['parent']);
		$shoot_result['season_id'] = $shoot_info['parent'];
		$shoot_result['avg_for_class'] = wpts_wwtsl_shoots_for_classes($shoot_info['parent'], $shoot->term_taxonomy_id, $shoot->post_author);
		$shoot_result['class_scores'] = wpts_calculate_class($shoot_result['avg_for_class']);
		$shoot_result['avg'] = wpts_season_avg($shoot_info['parent'], $shoot->term_taxonomy_id, $shoot->post_author);
		$description = unserialize($shoot_info['description']);
		$shoot_result['date'] = $description['date'];
		$shoot_result['first_miss'] = get_post_meta($shoot->ID,'first_miss', true);

return $shoot_result;
}


/*
 * $shooter_id = string id of shooter
 * $shoots = array of shoots to get score for
 *
 * return $season_of_shooter array
 */
function wpts_get_shooter_season($shooter_id, $shoots, $season_id){
	global $wpdb;
	$sum = 0;
	$count = 0;
	foreach ($shoots as $shoot){

		$sql = "SELECT * from $wpdb->posts
		LEFT JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.id
		WHERE `".$wpdb->posts."`.`post_type` = 'wpts_shoot'
		AND `".$wpdb->term_relationships."`.`term_taxonomy_id` = $shoot
		AND `".$wpdb->posts."`.`post_author` = $shooter_id ";
		$result = $wpdb->get_row($sql);
		if (! empty($result) ){
			$season_of_shooter["$shoot"] = wpts_shoot_result_to_array($result);
			$sum += (float)$season_of_shooter["$shoot"]["score"];
			$count++;
		}
	}


$avg = $sum/$count;
$shooter_info = get_userdata( $shooter_id );
$season_of_shooter['fname'] = $shooter_info->user_firstname;
$season_of_shooter['lname'] = $shooter_info->user_lastname;
$season_of_shooter['shooter_club'] =  $shooter_info->shootclub;
$latest_shoot_id = wpts_latest_shoot($shoots);
$avg = wpts_wwtsl_shoots_for_classes($season_id, $latest_shoot_id, $shooter_id);
$season_of_shooter['class'] = wpts_calculate_class($avg);

$season_of_shooter['concur'] = wpts_con_class($shooter_info->bday ,$season_id );


return $season_of_shooter;
}

/* take an array of shoot ID's, return the latest one */

function wpts_latest_shoot($shoots){

	foreach ( $shoots as $shoot_id ){
		$shoot = get_term_by('id', $shoot_id, 'wpts_shoots', $output = ARRAY_A);
		$shootdata = unserialize( $shoot['description'] );
		$date = $shootdata['date'];
		$date = (int) $date{0} . (int) $date{1} . (int) $date{2} . (int) $date{3} . (int) $date{5} . (int) $date{6} . (int) $date{8} . (int) $date{9};
		$the_dates[$date] = $shoot_id;
	}
	ksort( $the_dates );
	$latest_shoot = array_pop($the_dates);
	return $latest_shoot;
}


function wpts_get_shooters_in_season($shoots){
		global $wpdb;
	$sql = "SELECT DISTINCT post_author FROM $wpdb->posts
	LEFT JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.id
	WHERE `$wpdb->posts`.`post_type` = 'wpts_shoot'
	AND `$wpdb->term_relationships`.`term_taxonomy_id` IN ($shoots);
	";
	$shooters = $wpdb->get_col($sql);
	return $shooters;
}

function wpts_get_shoots_for_avg($season_id, $shoot_id, $shooter_id = false, $max = false , $average = true){

		$shoots_in_season = wpts_get_season_shoots($season_id);
	foreach ($shoots_in_season as $shoot){
		$shootdata = unserialize( $shoot['description'] );
		$date = $shootdata['date'];
		$date = (int) $date{0} . (int) $date{1} . (int) $date{2} . (int) $date{3} . (int) $date{5} . (int) $date{6} . (int) $date{8} . (int) $date{9};
		$id = $shoot['term_id'];
		if ($shoot['term_id'] === $shoot_id)
			$last_to_use = $date;
		$shoots_for_classes["$id"] = $date;
	}
	asort($shoots_for_classes);
	if ($max){
		$max = (int) $max;
		$shoots = array_slice($shoots_for_classes, 0, $max, true);
	}
	else
		$shoots = $shoots_for_classes;
	$shoots_to_use = '';
	foreach ($shoots as $id => $shoot){
		if ($last_to_use >= $shoot)
			$shoots_to_use .= " '$id' ,";
	}
	$shoots_to_use = substr_replace($shoots_to_use, "", -1);

	if (! $average && ! $shooter_id ){
		return $shoots_to_use;
		break;
	}
	global $wpdb;
	$sql = "SELECT post_title FROM $wpdb->posts
	LEFT JOIN $wpdb->term_relationships ON $wpdb->term_relationships.object_id = $wpdb->posts.id
	WHERE `$wpdb->posts`.`post_type` = 'wpts_shoot'
	AND `$wpdb->posts`.`post_author` = '$shooter_id'
	AND `$wpdb->term_relationships`.`term_taxonomy_id` IN ($shoots_to_use);
	";
	$scores = $wpdb->get_col($sql);
	return $scores;

}

function wpts_season_avg($season_id, $shoot_id, $shooter_id){
	$scores = wpts_get_shoots_for_avg($season_id, $shoot_id, $shooter_id);
	$a=0;
	$sum = 0;
	if ($scores){
		foreach ($scores as $score){
			$sum += (float)$score;
			$a++;
		}
	$it = (float)$sum/$a;
	} else {
	return false;
	break;
	}
	return $it;
}

function wpts_get_season_data( $shoot_id){
	// take the shoot_id, get the season ID, get the list of shoot ID's that took place before this one and get all of the data for each

	/*  Array [shooter] - [fname] [lname] [class] [concur] [club] [shoot [name] [id] [score] ]
	 * [shoots] [id] [name]
	 */


$shoots_info = get_term_by('id', $shoot_id, 'wpts_shoots', $output = ARRAY_A);
$shoots_in_season = wpts_get_shoots_for_avg($shoots_info['parent'], $shoot_id, $shooter_id = false, $max = false , $average = false);
$shoots = str_replace("'", '', $shoots_in_season);
$shoots = str_replace(" ", '', $shoots);
$shoots = explode(',', $shoots);
foreach ($shoots as $shoot){
	$season_shoots[$shoot] = get_term_by('id', $shoot, 'wpts_shoots', $output = ARRAY_A);
}
$season_info['shoots'] = $season_shoots;

$shooters = wpts_get_shooters_in_season($shoots_in_season);
$season_info['shooters'] = $shooters;
foreach ($shooters as $shooter_id)
	$shooter_info[] = wpts_get_shooter_season($shooter_id, $shoots, $shoots_info['parent']);
$season_info['theshoots'] = $shooter_info;
return $season_info;

}


function wpts_ind_shoot_result_table($shoot_id){
// Last, First, Score, Avg, Class, Rank, 1st Miss
	$shootdata = wpts_get_shoot_data($shoot_id);
	if (! $shootdata ){
		return false;
		break;
	}
	ob_start(); {
		echo "<table class='tablesorter'>
				<thead>
				<tr>
					<th>Last</th>
					<th>First</th>
					<th>Score</th>
					<th>Avg</th>
					<th>Class</th>
					<th>1st Miss</th>
					<th>Con Class</th>
					</tr>
				</thead>";

		foreach ($shootdata as $key => $shoot){
			extract($shoot);
			echo "<tr>
				<td>".$shooter_name['last']."</td>
				<td>".$shooter_name['first']."</td>
				<td>$score</td>
				<td>$avg</td>
				<td>$class_scores</td>
				<td>$first_miss</td>
				<td>$conclass</td>
			</tr>";

			//var_dump ($shoot);
		}
		//var_dump($shootdata);

	echo "</table>";


	$table = ob_get_clean();
	 }
	return $table;
}

function wpts_extra_profile_fields_show( $user ) { ?>

	<h3>Target Shooting Information</h3>

	<table class="form-table">

		<tr>
			<th><label for="shootclub">Shoot Club</label></th>

			<td>
				<input type="text" name="shootclub" id="shootclub" value="<?php echo esc_attr( get_the_author_meta( 'shootclub', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Please enter the club this user is affiliated with.</span>
			</td>
		</tr>

		<tr>
			<th><label for="bday">Birth Date</label></th>

			<td>
				<input type="text" name="bday" id="bday" value="<?php echo esc_attr( get_the_author_meta( 'bday', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Please enter the Birthday (YEAR/MONTH/DAY i.e. 1952/03/11 )  </span>
			</td>
		</tr>
	</table>
<?php }

function wpts_extra_profile_fields_edit( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;

	update_usermeta( $user_id, 'bday', $_POST['bday'] );
	update_usermeta( $user_id, 'shootclub', $_POST['shootclub'] );
}

?>